const express = require('express')
const router = express.Router()
const userDb = require('../db/user-db')
const {logI} = require('../log.js')
const {retError, retSuccess} = require('../utils/ret')
const checkType = require('../utils/checkType')
const checkToken = require('../utils/checkToken')
const checkDeviceNo = require('../utils/checkDeviceNo')
const moment = require('moment')

router
    .post('/', async(req, res) => {
        let {body: {maddr,deviceNo,token,meshUUID,buildingUUID}} = req
        logI("A-S", maddr, "mesh", `${JSON.stringify(req.body)}`, "null")
        try{
            const error = checkType.mesh(req.body)
            if(error){
                retError("mesh",maddr, 10001,  error.details[0].message, res);
            }else{
                let msg = {};
                msg = await checkToken(token,maddr);
                if(msg.code === 0){
                    const deviceInfo={
                        'maddr':maddr,
                        'deviceNo':deviceNo
                    }
                    let device={};
                    device = await checkDeviceNo(deviceInfo);
                    if(device.code === 0){
                        let result = {};
                        result = await userDb.selectMesh(maddr,buildingUUID,meshUUID,meshUUID);
                        const msg = {
                            "meshList": []
                        }
                        if(result){
                            for(let i =0;i<result.length;i++){
                                if(result[i].profile!=="")
                                    result[i].profile = "https://" + process.env.DOMAIN +result[i].profile;
                                if(result[i].image!=="")
                                    result[i].image = "https://" + process.env.DOMAIN +result[i].image;
                                result[i].createTime = moment(result[i].createTime).format('YYYY-MM-DD HH:mm:ss')
                            }

                            msg.meshList = result;
                        }
                        retSuccess("mesh", maddr,0, msg, res);
                    }else{
                        retError("mesh", maddr,device.code, device.body, res);
                    }
                }else{
                    retError("mesh", maddr,msg.code, msg.body, res);
                }
            }
        } catch (e) {
            retError("mesh", maddr,10001, e, res);
        }
    })
module.exports = router
